package com.hua.yuan.live.repertory.cloud_data.loader;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.alibaba.fastjson.JSONObject;
import com.hua.yuan.common.https.OkHttpModule;
import com.hua.yuan.live.LiveModule;
import com.hua.yuan.live.repertory.cloud_data.JsonResult;
import com.hua.yuan.live.repertory.cloud_data.api.LivePlayApi;
import com.hua.yuan.live.repertory.cloud_data.res.UserSigBean;
import com.hua.yuan.rtcroom.RTCRoom;
import com.hua.yuan.rtcroom.sdk.LoginInfo;
import java.io.IOException;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Response;

/**
 * rtc room loader
 */
public class UserSigLoader {

    private LivePlayApi mApi;

    private Disposable mPublish;

    public UserSigLoader() {
        mApi =OkHttpModule.getInstance().getRetrofit().create(LivePlayApi.class);
    }


    public interface  UserSigCallback{

        void onSuccess(boolean isSuccess);

        void onFailure(Throwable e);
    }


    /**
     * 获取主播的接口数据
     *
     * @param pToken    用户登录的token
     *
     */
    public void requestSig(@NonNull final String pToken,@NonNull final Context pContext,
                                @NonNull final UserSigCallback pCallback) {
        if(mPublish!=null){
            mPublish.dispose();
        }
        Observable.create(new ObservableOnSubscribe<UserSigBean>() {

            @Override
            public void subscribe(ObservableEmitter<UserSigBean> pEmitter) throws Exception {
                Call<String> call = mApi.getUserSig(pToken,LiveModule.RTC_TYPE);
                try {
                    Response<String> response = call.execute();
                    if (TextUtils.isEmpty(response.body())) {
                        pEmitter.onComplete();
                        return;
                    }
                    JsonResult<JSONObject> resultData = JSONObject.parseObject(response.body(), JsonResult.class);
                    if (resultData == null) {
                        pEmitter.onComplete();
                        return;
                    }
                    JSONObject data = resultData.getData();
                    if (data == null) {
                        pEmitter.onComplete();
                        return;
                    }
                    UserSigBean targetData = JSONObject.parseObject(data.toJSONString(), UserSigBean.class);
                    if (targetData == null) {
                        pEmitter.onComplete();
                        return;
                    }
                    pEmitter.onNext(targetData);
                } catch (IOException e) {
                    e.printStackTrace();
                    pEmitter.onError(e);
                }
            }

        }).subscribeOn(Schedulers.newThread())
                .map(new Function<UserSigBean, Boolean>() {

                    @Override
                    public Boolean apply(UserSigBean userSigBean) throws Exception {
                        initRoomSDK(userSigBean, pContext, pCallback);
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean playBean) throws Exception {

                    }
                });
    }


    /**
     * 初始化
     */
    private void initRoomSDK(UserSigBean sigBean, final Context pContext, final UserSigCallback callback) {

        LoginInfo info = new LoginInfo();
        info.sdkAppID = 1400120590;
        info.accType = "33255";
        info.userAvatar = "";
        info.userID = sigBean.getUid();
        info.userName = "";
        info.userSig =sigBean.getUsersig() ;


        String serverDomin = "https://room.qcloud.com/weapp\n" +
                "/double_room";

        LiveModule.getRtcRoom(pContext).login(serverDomin, info, new RTCRoom.LoginCallback() {
            @Override
            public void onError(final int errCode, final String errInfo) {
                callback.onFailure(new Exception(errInfo));
            }

            @Override
            public void onSuccess(String userId) {
                if(userId==null){
                    callback.onSuccess(false);
                }else{
                    callback.onSuccess(true);
                }
            }
        });
    }
}
